define([ "jquery",
         "comm","site_tip","upload/comm","files/file","mustache.min","plugin/plupload/moxie","plugin/plupload/plupload.dev","plugin/jquery.cookie"],
         function($,comm,Site_tip,uploadCom,File,Mustache) {

	/*var Files;
	require(['files/main'],function (f){
		Files = f;
	});*/
	
	var site_tip = new Site_tip();
	var checkInterval;
	
	function Upload(btn,form) {
		btn = btn || "file_add";
		this.container = form||$("#upload_form");
		this.uploader = null;
		this.changeFlag = false;
		this.isScroll = false;
		this.clearProId = 0;
		this.uArr = new Array();
		this.btn = btn;
		this.dropEl = btn=="file_add"?"wfo":"";
	}
	
	Upload.prototype.init = function() {
//		comm.loadCss("/static/js/jquery/jquery-scrollbar/jquery.mCustomScrollbar.css");
		this._bindUI();
	}
	
	Upload.prototype._bindUI = function() {
		var that = this;
		

		this.createPupload();
		$("#processWindow").off();
		// 显示上传进度框
		$("#processWindow").on("mouseenter",function(e) {
			if (that.is_over)
				return;
			if ($("#upload-procr-menu").css("display") == "none")
				return;
			$('#upload-procr').stop(true, false).slideDown("fast");
			that.is_over = true;
			that.pro_stop_animal.apply(that);
		});

		// 隐藏上传进度框
		$("#processWindow").on("mouseleave",function(e) {
			if (!that.is_over) {
				return;
			}
			that.is_over = false;
			that.proWindow_close.apply(that);
			/*
			that.pro_start_animal.apply(that);
			*/
		});
		//console.log("onbeforeunload");
		// 离开页面时保存文档
		/*window.onbeforeunload = function() {
			//console.log("onbeforeunload");
			if (that.changeFlag == true) {
				// 如果changeFlag的值为true则提示
				return '该操作会导致文件上传中断，是否继续';
			}

		}*/
		
		$("#upload_form").on("mouseenter","div",function(e){
			$(".tool-view").find(".icon_upload_bg").addClass("hover");
		});
		
		$("#upload_form").on("mouseleave","div",function(e){
			$(".tool-view").find(".icon_upload_bg").removeClass("hover");
		});
	}
	Upload.prototype.bindBeforeunload = function(){
		window.onbeforeunload = function(){
			//console.log(arguments);
			return '该操作会导致文件加密中断，是否继续';
		}
	}
	Upload.prototype.unbindBeforeunload = function(){
		window.onbeforeunload = null;
	}
	Upload.prototype.add_pro = function(file,up) {
		//console.log(file);
		var that = this;
		var view = {
			"id" : file.id,
			"type" : comm.get_file_type(file.name),
			"name" : file.name
		};
		var tmpl = $('#proTpl').html();
		var item_text = Mustache.render(tmpl, view);
		$('#procr_panel').append(item_text);
		
		var uploaded = this.uploader.total.uploaded;
		var queued = this.uploader.total.queued;
		var failed = this.uploader.total.failed;
		var index = uploaded + queued + failed;
		if (index % 2 == 0) {
			$("#"+file.id).css("background-color", "#fafafb");
		}
		
		var pro_del = $("#"+file.id).find(".icon-del");
		pro_del.on("click",function(e){
			comm.stopEvent(e);
			var id = $(this).parents(".item").attr("id");
			up.removeFile(file);
			$("#"+file.id).remove(); 
			that.checkPro();
			that.uploading_status.apply(that);
		});
		
		var errs = $('#procr_panel').find(".item[status='1']");
		$(errs).each(function(){
			var filename = $(this).find(".name").text();
			if(filename == file.name){
				var reItem = that.uploader.getFile($(this).attr("id"));
			//	that.uploader.removeFile(reItem);
				that.checkPro();
				that.uploading_status.apply(that);
				$(this).remove();	
			}
		});
		
		that.checkPro.apply(that);
	}
	
	Upload.prototype.uploading_status = function() {
		//var uploaded = this.uploader.total.uploaded;
		var uploaded = $("#processWindow").find(".item[status='0']").size();
		//var queued = this.uploader.total.queued;
		var queued = $("#processWindow").find(".item[status='-1']").size();
		//var failed = this.uploader.total.failed;
		var failed = $("#processWindow").find(".item[status='1']").size();
		var len = parseInt(uploaded) + parseInt(queued) + parseInt(failed);
		/*var pack = $("#processWindow").find(".packing-mark").size();
		//console.log(pack);
		uploaded-=pack;
		queued+=pack;*/

		/*var error =$("#processWindow").find(".item[status=1]").size();
		uploaded-=error;
		failed+=error;
		queued-=error;*/
		if(queued > 0){
			$("#processWindow").find(".loading").css("display", "block");
			$("#upload-procr-menu")
					.html("加密中 " + uploaded + "/" + len);
			return;
		}
		
		$("#processWindow").find(".loading").css("display", "none");
		//this.changeFlag = false;
		//解绑页面刷新时间
		this.unbindBeforeunload();
		var itemLen = $("#procr_panel").children().length;
		if (itemLen == 0) {
			this.pro_stop_animal();
			this.clearPro();
			return;
		}
		
		
		if(failed == len){
			$("#upload-procr-menu")
					.html(len+"个文件加密失败&nbsp;&nbsp;<a href='#' id='pro-clean' class='inner-tip'>清空</a>");
			
		}else if(failed > 0 && failed <len){
			$("#upload-procr-menu")
					.html(uploaded+"个文件加密成功，"+failed+"个失败&nbsp;&nbsp;<a href='#' id='pro-clean' class='inner-tip'>清空</a>");
		}else {
			$("#upload-procr-menu")
					.html("加密完毕");
		}
		$('#close_pro_win').show();
		
		var that = this;
		$("#pro-clean").off().on("click", function(e) {
			comm.stopEvent(e);
			
			that.pro_stop_animal();
			that.clearPro();
			
			if($(this).text() == "查看"){
				var e = jQuery.Event("fileUpload.see");
				that.container.trigger(e);
			}
			
		});
		
		$('#close_pro_win').on('click', function(e){
			comm.stopEvent(e);
			
			that.pro_stop_animal();
			that.clearPro();
		})
		
			
	}
	
	Upload.prototype.uploading_err = function(file) {
		var item = $("#"+file.id);
		item.find(".icon-del").parent().css("display", "none");
		item.find(".icon-err").parent()
				.css("display", "table-cell");
		item.find(".bar").width(0);
		this.uploading_status();
		item.find(".percent").html('');
	}
	
	Upload.prototype.proWindow_close = function(){
		$('#upload-procr').stop(true, false).slideUp("fast");
	}
	
	Upload.prototype._show_suc_statu = function(id) {
		var that = this;
		return function() {
			that.show_suc_statu(id);
		}
	}
	
	Upload.prototype.show_suc_statu = function(id) {
		var item = $("#"+id);
		item.find(".percent").html('');

		item.find(".icon-suc").parent().css("display", "table-cell");

		item.find(".bar").css('width', '0');
	}
	
	Upload.prototype.checkPro = function() {
		if($("#upload-procr").height()<200){
			var item = $("#procr_panel").find(".item");
			var p_height= item.size()*46;
			$("#upload-procr").height(p_height);
		} else if ($("#upload-procr").height() > 200 && !this.isScroll) {
			$("#upload-procr").height(229);
			this.isScroll = true;
			/*$("#upload-procr").mCustomScrollbar({
				theme : "minimal"
			});*/
		} else{
			var item = $("#procr_panel").find(".item");
			var p_height= item.size()*46;
			$("#upload-procr").height(p_height);
			
			if($("#upload-procr").height() > 200){
				$("#upload-procr").height(229);
			}
		}
	}
	
	Upload.prototype._clearPro = function() {
		var that = this;
		return function() {
			that.clearPro();
		}
	}
	
	Upload.prototype.clearPro = function() {
		var uploaded = this.uploader.total.uploaded;
		var queued = this.uploader.total.queued;
		var failed = this.uploader.total.failed;
		if (queued > 0) {
			return;
		}
		this.resetData(true);
		this.clearProId = null;

		if(this.uArr != null){
			for(var i=0;i<this.uArr.length;i++){
				this.uploader.removeFile(this.uArr[i]);
				var file=this.uArr[i];
				$("#"+file.id).remove();
			}
		}
		$('#processWindow').hide();
		$('#close_pro_win').hide();
	}
	
	
	Upload.prototype.resetData = function(isEach) {
		//判断是否遍历过，是的话，就不遍历。
		if((isEach == undefined || !isEach) && $("#procr_panel").length >0){
			var size = $("#procr_panel").find(".item[status='1']").size();
			if(size > 0){
				return;
			}
		}
		$("#upload-procr").css('display', 'none');
		$("#upload-procr-menu").css('display', 'none');
		$("#upload-procr-menu").find("a").remove();
		$("#upload-procr-menu").html("");
		$("#upload-procr").height(0);

		$("#procr_panel").find(".item").remove();
	}
	
	Upload.prototype.pro_stop_animal = function() {
		if (this.clearProId != null || this.clearProId != undefined) {
			clearTimeout(this.clearProId);
			this.clearProId = null;
		}
	}
	
	Upload.prototype.pro_start_animal = function() {
		if($("#waterfall").height()<$("#mypage").height()){
			this.clearProId = setTimeout(this._clearPro(), 5000);
		}
	}
	$.uploadErrorCallback=function(that,file,ret){
		var item_msg;
		if(!ret)
		{
			item_msg="无法连接到服务器";
		}
		else if(ret.error_code && ret.error_code == 7002)
		{
			item_msg = "加密的文件类型不支持，<a href='/helpcenter?active=1' class='outer-tip' target='_blank'>查看帮助</a>";
		}
		else
		{
			item_msg = ret.message;
		}
		//tip_msg = item_msg;

		that.uploading_err.apply(that,[file]);
		if(that.uArr == null){
			that.uArr = new Array();
		}
		that.uArr.push(file);

		$("#"+file.id).find(".icon-err").attr("title", item_msg);
		var percent = $("#"+file.id).find(".percent");
		//percent.text(item_msg.length>12?item_msg.substring(0,10)+"...":item_msg);
		percent.html(item_msg);
		percent.addClass("err").attr("title",item_msg);

		$("#"+file.id).attr("status","1").removeClass("packing-mark");
		site_tip.setContent(item_msg, true, false);
		//that.uploader.total.uploaded=that.uploader.total.uploaded>0?that.uploader.total.uploaded-1:0;
		//that.uploader.total.queued;
		//that.uploader.total.failed++;
		//console.log(that.uploader.total.uploaded);
		that.uploading_status();
	}
	
	
	Upload.prototype.uploadCheck =function(f,up){
		 var that =this;
		 var folder_id=f.folder||0;
		 var file_size=f.size;			
			$.ajax({
				    type : "post",
			        async : true, //同步执行
			        url : "/upload_check",	
			        data:{file_size:file_size,folder_id:folder_id},
			        dataType : "json", //返回数据形式为json						       
			        success : function(ret) {	
			        	if(ret!=null){
			        		if(ret.error_code!=0){
			        			var item_msg=ret.message;
			        			that.uploading_err.apply(that,[f]);
								if(that.uArr == null){
									that.uArr = new Array();
								}
								that.uArr.push(f);
								
								$("#"+f.id).find(".icon-err").attr("title", item_msg);
								var percent = $("#"+f.id).find(".percent");
								
								percent.addClass("err");
								
								$("#"+f.id).attr("status","1");
								//site_tip.setContent(item_msg, true, false);
								clearInterval(checkInterval);
			                	up.removeFile(f);	
			                	percent.text(item_msg);
			                	that.checkPro();
			                	that.uploading_status();
			        		}						        								        		
			        	}else{
			        		
			        	}						               			                
			        },
			        error : function(ret){
			        	 var item_msg="无法连接到服务器";
							that.uploading_err.apply(that,[f]);
							if(that.uArr == null){
								that.uArr = new Array();
							}
							that.uArr.push(f);
							
							$("#"+f.id).find(".icon-err").attr("title", item_msg);
							var percent = $("#"+f.id).find(".percent");
							
							percent.addClass("err");
							
							$("#"+f.id).attr("status","1");
							site_tip.setContent(item_msg, true, false);
							clearInterval(checkInterval);
		                	up.removeFile(f);	
		                	percent.text(item_msg);
		                	that.checkPro();
		                	that.uploading_status();
			        }
			});
	}
	Upload.prototype.createPupload = function(){
		var that = this;
		var s_id = $("#s_id").val();
        //console.log("hahah");
		this.uploader = new plupload.Uploader({
			runtimes : 'html5,flash,html4',
			browse_button : that.btn, // you can pass in id...
			url : '/upload',
			flash_swf_url : '/static/js/jquery/plupload/Moxie.swf',
			silverlight_xap_url : '/static/js/jquery/plupload/Moxie.xap',
			drop_element :that.dropEl,
			headers:{"x-csrf-token": $.cookie("__CSRF__")||""},
			//max_file_size: '1000mb',
			//chunk_size: '4mb',
			filters: {
				  mime_types : [
					{ title : "易控支持的文件类型", extensions:"jpg,gif,png,jpeg,bmp,psd,pdf,doc,docx,xls,xlsx,ppt,pptx,ai,txt,cdr,dwg,wav,wma,flac,mp4,3gp,rmvb,mpg,avi"},
				    { title : "图像文件（.jpg,.gif,.png,.jpeg,.bmp）", extensions : "jpg,gif,png,jpeg,bmp" },
				    { title : "PSD文件（.psd）", extensions : "psd" },
				    { title : "PDF文件（.pdf）", extensions : "pdf" },
				    { title : "Word文档（.doc,.docx）", extensions : "doc,docx" },
				    { title : "Excel表格（.xls,.xlsx）", extensions : "xls,xlsx" },
				    { title : "PPT幻灯片（.ppt,.pptx）", extensions : "ppt,pptx" },
				    { title : "AI文件（.ai）", extensions : "ai" },
				    { title : "文本文件（.txt）", extensions : "txt" },
				    { title : "CDR文件（.cdr）", extensions : "cdr" },
				    { title : "DWG文件（.dwg）", extensions : "dwg" },
					{ title : "音频文件（.mp3,.wav,.wma,.flac）", extensions:"mp3,wav,wma,flac"},
					{ title : "视频文件（.mp4,.3gp,.rmvb,.mpg,.avi）", extensions : "mp4,3gp,rmvb,mpg,avi"}
				  ]
			},
			init: {
                PostInit: function() {

                },
				BeforeUpload:function(up,f){
					//that.uploader.setOption("multipart_params",{folder_id:f.folder});               	
                	checkInterval=setInterval(function(){
						var folder_id=f.folder||0;
						var file_size=f.size;			
						$.ajax({
								type : "post",
								async : true, //同步执行
								url : "/upload_check",	
								data:{file_size:file_size,folder_id:folder_id},
								dataType : "json", //返回数据形式为json						       
								success : function(ret) {	
									if(ret!=null){
										if(ret.error_code!=0){
											var item_msg=ret.message;
											that.uploading_err.apply(that,[f]);
											if(that.uArr == null){
												that.uArr = new Array();
											}
											that.uArr.push(f);
											
											$("#"+f.id).find(".icon-err").attr("title", item_msg);
											var percent = $("#"+f.id).find(".percent");
											
											percent.addClass("err");
											
											$("#"+f.id).attr("status","1");
											//site_tip.setContent(item_msg, true, false);
											clearInterval(checkInterval);
											up.removeFile(f);	
											percent.text(item_msg);
											that.checkPro();
											that.uploading_status();
										}						        								        		
									}else{
										
									}						               			                
								},
								error : function(ret){
									 var item_msg="无法连接到服务器";
										that.uploading_err.apply(that,[f]);
										if(that.uArr == null){
											that.uArr = new Array();
										}
										that.uArr.push(f);
										
										$("#"+f.id).find(".icon-err").attr("title", item_msg);
										var percent = $("#"+f.id).find(".percent");
										
										percent.addClass("err");
										
										$("#"+f.id).attr("status","1");
										site_tip.setContent(item_msg, true, false);
										clearInterval(checkInterval);
										up.removeFile(f);	
										percent.text(item_msg);
										that.checkPro();
										that.uploading_status();
								}
						});
					},1000);  
					that.uploader.setOption("url",'/upload?folder_id='+(f.folder||0));
					//console.log(that.uploader.getOption("multipart_params"));
				},

                //添加文件列表
				FilesAdded: function(up, files) {
					//console.log(files);
					$("#processWindow").css('display', 'block');
					$("#upload-procr-menu").css('display', 'inline-block');
					$("#upload-procr").css("display", "block");
					$('#close_pro_win').hide();

					//that.changeFlag = true;
					//绑定刷新页面事件
					that.bindBeforeunload();						
					plupload.each(files, function(file,index) {							
						file.folder = $("#folderPath [haslast]").attr("uuid");
					    that.add_pro.apply(that,[file,up]);
					    that.uploading_status.apply(that);	
						//console.log($("#folderPath [haslast]").attr("uuid"));
						//console.log(files);
                        
					});

					$("#upload-procr").animate({scrollTop:$("#upload-procr .panel-inner").height()});
					//console.log("status....");
					//console.log(that.uploader);
					if(that.uploader.state==1)
					{
						that.uploader.start();
					}

				},
				
				FilesRemoved:function(up,files){
				//	plupload.each(files, function(file) {
				//		$("#"+file.id).remove();
				//	});
				},	

                //上传进度
				UploadProgress: function(up, file){
					file.percent = file.percent || 0;
					//console.log(file.percent);
					//console.log(file.percent);
					var percent = Math.round(file.percent*0.9);
					$("#"+file.id).find(".percent").html(percent + '%');
					$("#"+file.id).find(".bar").width(percent + '%');
				},

                //单文件上传完成
				FileUploaded: function(uploader,file,responseObject){
					//console.log(file);
					//console.log("ssss");return;
					//console.log(that.uploader.total.uploaded);
					//that.uploader.total.uploaded--;
					clearInterval(checkInterval);
					var response = parseObj(responseObject.response);
					if(!response.success)
					{
						$.uploadErrorCallback(that,file,response);
						return false;
					}
					$("#"+file.id).addClass("packing-mark").find(".icon-del").text("加密中...").addClass("file-packing").off().parent().attr("title","加密中");
					var percent_process,percent_timer,error_num=0;
					function getPacketPercent()
					{
						percent_process=$.ajax({
							url:"/files/get_packet_percent",
							data:{id:response.guid},
							dataType:'json',
							success:function(ret)
							{
								if(!ret.success)
								{

									$("#"+file.id)/*.attr("status","0")*/.removeClass("packing-mark");
									$.uploadErrorCallback(that,file,ret);
									//that.uploader.total.queued--;
									//that.uploader.total.uploaded--;
									//that.uploader.total.failed++;
									//error_num++;
									//percent_timer=setTimeout(getPacketPercent,1000);
									return;
								}
								ret.percent = parseInt(ret.percent)||10;
								if(ret.percent>=100)
								{
									//var data = ret.data;
									$("#"+file.id).find(".icon-del").parent().css("display","none");
									$("#"+file.id).find(".bar").css('width', '100%');
									$("#"+file.id).attr("status","0").removeClass("packing-mark");
									//console.log("suc");
									setTimeout(that._show_suc_statu.apply(that,[file.id]), 100);

									that.uploading_status();

									//如果上传完成的文件的文件夹id是当前文件夹的id,则添加至页面
									if (file.folder ==  $("#folderPath [haslast]").attr("uuid")) {
										var e = jQuery.Event("fileUpload.add");
										//console.log(ret.data);
										e.file = ret.data;
										that.container.trigger(e);
									}

									/*
									 that.pro_stop_animal.apply(that);
									 that.pro_start_animal.apply(that);
									 */
									$("#selAllFiles").find(".icon-checkbox").removeClass("hover");

									if(that.uArr == null){
										that.uArr = new Array();
									}
									//file.uuid = file.id;
									that.uArr.push(file);
								}
								else
								{
									var percent  = Math.round(90+(ret.percent)*0.1);
									percent=percent>=100?99:percent;
									$("#"+file.id).find(".percent").html(percent + '%');
									$("#"+file.id).find(".bar").width(percent + '%');
									percent_timer=setTimeout(getPacketPercent,1000);
								}
							},
							error:function(){
								/*if(error_num>5)
								{
									$.uploadErrorCallback(that,file,{message:"网络错误"});
									return false;
								}
								error_num++;*/
								percent_timer=setTimeout(getPacketPercent,1000);
							}
					});
					}
					getPacketPercent();

				},
                //上传完成
				UploadComplete: function(uploader,files){
				},

                //系统报错
				Error: function(up, err) {
					//console.log(up);
					//console.log(err);
					var item_msg="无法连接到服务器";
					//console.log(err);
					if (err.status == 411 || err.code == -603) {
						item_msg = "加密的文件为空文件";
					}else if (err.status == 415 || err.code == -601) {
						item_msg = "加密的文件类型不支持，<a href='/helpcenter?active=1' class='outer-tip' target='_blank'>查看帮助</a>";
					}else if (err.status == 413) {
						item_msg = "空间不足，请扩容或者删除历史文件再加密";
					}else if (err.status == 408) {
						item_msg = "加密超时";
					}else if (err.status == 500) {
						item_msg = "系统繁忙";
					}
					/*if(err.code && err.code == 7002)
					{
						item_msg = "上传的文件类型不支持，<a href='/helpcenter?active=1' class='outer-tip' target='_blank'>查看帮助</a>";
					}
					else
					{
						item_msg = err.msg;
					}*/
						
					//tip_msg = item_msg;
					
					var file = err.file;
					
					that.uploading_err.apply(that,[file]);
					if(that.uArr == null){
						that.uArr = new Array();
					}
					that.uArr.push(file);
					
					$("#"+file.id).find(".icon-err").attr("title", item_msg);
					var percent = $("#"+file.id).find(".percent");
					percent.text(item_msg);
					percent.addClass("err");
					
					$("#"+file.id).attr("status","1");
					site_tip.setContent(item_msg, true, false);
					
				}
			}
		});

		this.uploader.init();
	}
	
	function parseObj( strData ){
        return (new Function( "return " + strData ))();
	}
	
	return Upload;
});
